#include "MAF.h"
#include <stdint.h>
#include <stdio.h>


// 初始化滤波器
static void WHT_WindowFilter_Init(WHT_MAF_t* filter, float* buffer, unsigned short windowSize)
{

    filter->buffer = buffer;
    filter->size = windowSize;
    filter->index = 0;
    filter->count = 0;
    filter->sum = 0.0f;

    for (unsigned int i = 0; i < filter->size; i++)
    {
        filter->buffer[i] = 0.0f;
    }
}

// 添加新数据并返回滤波结果
static float WHT_WindowFilter_Update(WHT_MAF_t* filter, float new_value)
{
    if (filter->size == 0) return new_value; // 避免除零

    // 窗口已满
    if (filter->count == filter->size)
    {
        filter->sum -= filter->buffer[filter->index];
    }
    else
    {
        filter->count++;
    }

    // 累加
    filter->buffer[filter->index] = new_value;
    filter->sum += new_value;

    // 更新索引（循环缓冲区）
    filter->index = (filter->index + 1) % filter->size;

    // 返回平均值
    return filter->sum / (float)filter->count;
}

// 获取当前输出值（不更新状态）
static float WHT_Get_Current_Output_Value(const WHT_MAF_t *filter)
{
    return filter->sum / (float)filter->count;
}

const WHT_MAF_OPS_t WHT_MAF_OPS =
{
    .init               = WHT_WindowFilter_Init,
    .apply_update       = WHT_WindowFilter_Update,
    .get_current_output = WHT_Get_Current_Output_Value,
};


// 使用示例
int main_MAF(void)
{
    float buffer[10];
    WHT_MAF_t filter;

    WHT_WindowFilter_Init(&filter, buffer, sizeof(buffer)/ sizeof(buffer[0]));

    float raw_data[] = {1.0, 1.2, 1.1, 1.3, 1.5, 2.0, 1.9, 1.8, 1.7, 1.6, 1.5};

    for (int i = 0; i < sizeof(raw_data)/sizeof(float); i++)
    {
        float filtered = WHT_WindowFilter_Update(&filter, raw_data[i]);
        printf("Raw: %.2f, Filtered: %.2f\n", raw_data[i], filtered);
    }

    return 0;
}

